package api

import (
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
	"mime"
	"path/filepath"
	"project_api/intrenal/api/response"
	"strings"
	"time"
)

const (
	endpoint        = "117.27.231.112:9000"
	accessKeyID     = "BP8Gcyzz4wAGOQsBLhiD"
	secretAccessKey = "2eTlPvECvmmaoXlXfTXzcRlJKVvNgXsAnPtNXylt"
	bucketName      = "zg3"
	fileSize        = 1024 * 1024 * 100
)

func Upload(c *gin.Context) {

	var map1 = make(map[string]bool)
	map1[".mp4"] = true
	map1[".mp5"] = true

	// Initialize minio client object.
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
	})
	if err != nil {
		log.Fatalln(err)
	}

	file, err := c.FormFile("file")
	if err != nil {
		response.Response(c, 400, "文件获取失败", nil)
		return
	}

	open, err := file.Open()
	if err != nil {
		response.Response(c, 400, "文件打开失败", nil)
		return
	}

	if file.Size > fileSize {
		response.Response(c, 400, "文件最大只能为100mb", nil)
		return
	}

	lower := strings.ToLower(filepath.Ext(file.Filename))

	if !map1[lower] {
		response.Response(c, 400, "只能为视频", nil)
		return
	}

	extension := mime.TypeByExtension(lower)

	load, _ := time.LoadLocation("Asia/Shanghai")

	times := time.Now().In(load).Format("20060102150405")

	obj := times + "/" + file.Filename

	minioClient.PutObject(c, bucketName, obj, open, file.Size, minio.PutObjectOptions{ContentType: mime.TypeByExtension(extension)})

	URL := "http://" + endpoint + "/" + bucketName + "/" + obj

	response.Response(c, 200, "上传成功", URL)

}
